<template>
  <a-modal
    :title="model && model.id > 0 ? '编辑账户': '新增账户'"
    :width="640"
    :visible="visible"
    :confirmLoading="loading"
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <a-form-item label="id" v-show="false">
          <a-input v-decorator="['id']" />
        </a-form-item>
        <a-form-item label="账户名称">
          <a-input v-decorator="['accountName', { rules: [{ required: true, message: '请输入账户名称' }] }]" placeholder="请输入账户名称" />
        </a-form-item>
        <a-form-item label="联系电话">
          <a-input v-decorator="['phone', { rules: [{ required: true, message: '请输入联系电话' }] }]" placeholder="请输入联系电话" />
        </a-form-item>
        <a-form-item label="初始余额">
          <a-input v-decorator="['startAmount', { initialValue: 0 }]" addonAfter="元" placeholder="请输入初始余额"/>
        </a-form-item>
        <a-form-item label="备注">
          <a-textarea rows="2" v-decorator="['memo']" placeholder="请输入备注" />
        </a-form-item>
        <a-form-item v-if="model && model.id > 0" label="账户状态">
          <a-select v-decorator="['status']">
            <a-select-option value="1">可欠账</a-select-option>
            <a-select-option value="2">已停用</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>
  
  <script>
  import pick from 'lodash.pick'
  
  // 表单字段
  const fields = ['accountName','phone','startAmount','memo','status', 'id']
  
  export default {
    props: {
      visible: {
        type: Boolean,
        required: true
      },
      loading: {
        type: Boolean,
        default: () => false
      },
      model: {
        type: Object,
        default: () => null
      }
    },
    data () {
      this.formLayout = {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 7 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 13 }
        }
      }
      return {
        form: this.$form.createForm(this)
      }
    },
    created () {
      // 防止表单未注册
      fields.forEach(v => this.form.getFieldDecorator(v))
  
      // 当 model 发生改变时，为表单设置值
      this.$watch('model', () => {
        this.model && this.form.setFieldsValue(pick(this.model, fields))
      })
    }
  }
  </script>